package com.example.sendsms;

import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.sendsms.model.JsonRootBean;
import com.example.sendsms.model.Result;
import com.example.sendsms.utils.HttpUtil;
import com.example.sendsms.utils.Util;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private EditText et02;
    /// 电话
    List<Result> results = new ArrayList<>();
    // 对话框
    private ProgressDialog progressDialog;
    private MainAdapter adapter;
    private Result tel = new Result();
    private List<String> tels = new ArrayList<>();

    private List<String> ssss = new ArrayList<>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et02 = (EditText) findViewById(R.id.et02);
        Button b = (Button) findViewById(R.id.b);
        ListView listView = (ListView) findViewById(R.id.lv_main);
        adapter = new MainAdapter(results, this);
        listView.setAdapter(adapter);
        for (int i =0;i<1000;i++){
            ssss.add(String.valueOf(92808000+1));
        }
        listView.setOnItemClickListener((parent, view, position, id) -> {
            tel = results.get(position);
            tels = Arrays.asList(tel.getTel().split(","));
            for (int i = 0; i < tels.size(); i++) {
                Log.d("TAG", tels.get(i));
            }
        });
        showProgressDialog();
        sendRequest();
        //下面EditText的方法的作用是当点击编辑框时里面原先的内容消失，进入编辑状态
        et02.setOnClickListener(v -> {
            et02.setText("");
        });
        b.setOnClickListener(v -> {
            sendSMS(ssss);
        });
    }

    // 拨打电话号码
    public void sendSMS(List<String> numbers) {
        SmsManager sm = SmsManager.getDefault();
        String content = et02.getText().toString();
//        for (int i = 0; i < numbers.size(); i++) {
            if (isWithin70(content)) {
                /*
                  当两个判定条件都通过时发送短信，先构建一个PendingIntent对象并使用getBroadcast()广播
                  然后将PendingIntent，短信，电话号码等内容传入SmsManager的sendTextMessage()方法中*/
                try {
                    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent(), 0);
                    sm.sendTextMessage("928080011199999", null, content, pi, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Toast.makeText(MainActivity.this, "内容", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "短信内容超过70个字！请改正", Toast.LENGTH_LONG).show();
            }
//        }
    }

    //判断短信内容是否超过70个字
    public static boolean isWithin70(String s) {
        return s.length() <= 70;
    }

    //判断电话号码的格式是否正确
    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean valid;
        /*
          两种电话号码格式
          ^\\(? 表示可以以(开头
          (\\d{3}) 表示后面紧跟3个数字
          \\)? 表示可以以)继续
          [- ]? 表示在上述格式后面可以使用选择性的“-”继续
          (\\d{4}) 表示后面紧跟4个数字
          [- ]? 表示在上述格式后面可以使用选择性的“-"继续
          (\\d{4})$ 表示以4个数字结束
          综上所述：正确的电话号码的格式可以以下面等几种做为参考：
          (123)456-78900 123-456-78900 12345678900 (123)-456-78900*/
        String expression01 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        String expression02 = "^\\(?(\\d{3})\\)?[- ]?(\\d{5})[- ]?(\\d{5})$";
        //创建Pattern对象
        Pattern p01 = Pattern.compile(expression01);
        //将Pattern作为参数传入Matcher，当做电话号码phoneNumber的正确格式
        Matcher m01 = p01.matcher(phoneNumber);
        Pattern p02 = Pattern.compile(expression02);
        Matcher m02 = p02.matcher(phoneNumber);
        valid = m01.matches() || m02.matches();
        return valid;
    }

    private void sendRequest() {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(Util.address, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                closeProgressDialog();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                closeProgressDialog();
//                List<DataMsg> dataMsgs;
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    JSONArray jsonArray = jsonObject.getJSONArray("result");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject2 = (JSONObject) jsonArray.get(i);
                        String tel = jsonObject2.getString("tel");
                        Result result = new Result();
                        result.setTel(tel);
                        runOnUiThread(() -> {
                            results.add(result);
                            adapter.notifyDataSetChanged();
                        });
                    }
                } catch (JSONException e) {
                    Log.d("异常信息", e.getMessage());
                }
            }
        });
    }

    /**
     * 显示进度对话框
     */
    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    /**
     * 关闭进度对话框
     */
    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}